package com.yxq.mdt.app.modules.publish.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.personal.bean.PublishResult;
import com.yxq.mdt.app.modules.publish.ui.bean.MainPublishImageBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishImageFileBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishListBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishTopicInfo;
import com.yxq.mdt.app.modules.publish.ui.model.MainPublishModel;
import com.yxq.mdt.app.modules.publish.ui.presenter.IMainPublishContract;
import com.yxq.mdt.app.modules.publish.ui.presenter.MainPublishPresenter;
import com.yxq.mdt.app.modules.socialcontact.adapter.PublishImageListAdapter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialContactAllTopicsAc;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.widgets.OssHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * 发布图片
 */
public class PublishImageActivity extends BaseActivity<MainPublishPresenter> implements IMainPublishContract.View {
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.publish_topic)
    TextView publishTopic;
    @BindView(R.id.publish_select_circle)
    RelativeLayout publishSelectCircle;
    public int GOTOCIRCLE = 102;
    PublishImageListAdapter uploadImageListAdapter;
    @BindView(R.id.publish_img_recyclerView)
    RecyclerView publishImgRecyclerView;
    List<UploadImageBean> uploadImageBeanList;
    List<LocalMedia> images;
    @BindView(R.id.publish_image_content)
    EditText publishImageContent;
    @BindView(R.id.publish_image_content_words)
    TextView publishImageContentWords;
    @BindView(R.id.publish_image_btn)
    TextView publishImageBtn;
    String sort = "1", class2 = "1";
    int imageNumberSize = 0;
    int len = 0;
    List<String> imageList;
    @BindView(R.id.address_text)
    TextView addressText;
    @BindView(R.id.publish_image_content_check)
    CheckBox publishImageContentCheck;
    private String liftText;
    private String groupId = "", TopicOfConversation = "";
    PublishTopicInfo topicInfo;

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_image;
    }

    @Override
    public void initView() {
        if (!TextUtils.isEmpty(getIntent().getStringExtra("CircleId"))) {
            groupId = getIntent().getStringExtra("CircleId");
        }
        addressText.setText(Hawk.get(SPKey.SP_KEY_USER_ADDRESS_CITY_NAME));
        imageList = new ArrayList<>();
        //初始化图片上传控件
        publishImgRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        uploadImageBeanList = new ArrayList<>();
        uploadImageBeanList.add(new UploadImageBean());
        uploadImageListAdapter = new PublishImageListAdapter(uploadImageBeanList);
        publishImgRecyclerView.setAdapter(uploadImageListAdapter);
        publishImgRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 5, false));
        uploadImageListAdapter.setOnItemClickListener((adapter, view, position) -> {
            imageNumberSize = position;

            if (uploadImageListAdapter.getItem(position).getItemType() == -1) {
                selectImages();
            } else {
                //预览图片
                PictureSelector.create(mActivity).externalPicturePreview(position, images,1);
            }
        });
        uploadImageListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            List<UploadImageBean> uploadImageBeanList = uploadImageListAdapter.getData();
            if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                uploadImageBeanList.remove(position);
                //第一张不是添加图片，添加按钮
                List<UploadImageBean> temp = new ArrayList<>();
                temp.addAll(uploadImageBeanList);
                temp.add(new UploadImageBean());
                uploadImageListAdapter.setNewData(temp);
            } else {
                uploadImageListAdapter.remove(position);
            }
        });
        publishSelectCircle.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(publishImageContent.getText())) {
                if (publishImageContent.getText().toString().contains("#")) {
                    TopicOfConversation = publishImageContent.getText().toString().substring(publishImageContent.getText().toString().indexOf("#"), publishImageContent.getText().toString().lastIndexOf("#") + 1);
                    publishImageContent.setText(liftText);
                }
                TopicOfConversation = "";
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publishImage", "3");
                startActivityForResult(intent, GOTOCIRCLE);
            } else {
                publishImageContent.setHint("想和大家分享什么呢？");
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publishImage", "3");
                startActivityForResult(intent, GOTOCIRCLE);
            }

        });
        publishImageContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                publishImageBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                publishImageBtn.setTextColor(getResources().getColor(R.color.color_font_black));
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = publishImageContent.getText().toString();
                if (content.length() == 0) {
                    publishImageBtn.setBackgroundResource(R.drawable.shape_btn_lin_selector);
                    publishImageBtn.setTextColor(getResources().getColor(R.color.gray_pressed));
                } else {
                    publishImageBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                    publishImageBtn.setTextColor(getResources().getColor(R.color.color_font_black));
                }
                publishImageContentWords.setText(content.length() + "/" + 1000);

            }
        });
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new MainPublishPresenter(this, new MainPublishModel());
    }

    /**
     * 打开图片选择器
     */
    private void selectImages() {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(10 - uploadImageListAdapter.getData().size())//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //判断当前输入的文字跟上传的图片是否为空
    @SuppressLint({"AutoDispose", "CheckResult"})
    private void setContentIsNull() {
        if (uploadImageListAdapter.getData().size() > 1 || publishImageContent.getText().toString().trim().length() > 0) {
            //有图片或者文字
            List<String> imagesList = new ArrayList<>();
            for (UploadImageBean uploadImageBean : uploadImageListAdapter.getData()) {
                if (uploadImageBean.getItemType() != -1) {
                    imagesList.add(uploadImageBean.getPath());
                }
            }
            showLoadingDialog();

            if (imagesList.size() > 0) {
                imageList.clear();
                len = 0;
                Observable.fromIterable(imagesList)
                        .observeOn(Schedulers.io())
                        .map(path -> {
                            File file = new File(path);
                            OssHelper.getOss(mActivity, true).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP_VOICE + file.getName(), file.getPath()));
                            return OssHelper.getOssPrefixUrl(OssHelper.GS_APP_VOICE, file.getName());
                        })
                        .subscribe(s -> {
                            if (!TextUtils.isEmpty(s)) {
                                if (s != null) {
                                    len++;
                                }
                                imageList.add(s);
                                if (len == imagesList.size()) {
                                    publishImages();
                                }
                            }
                        }, throwable -> {
                            showBottomToast("上传失败请重新上传");
                            hideLoadingDialog();
                        });
            } else {
                //无图片
                if (publishImageContent.getText().toString().length() > 0) {
                    //是否上传地理位置
                    if (publishImageContentCheck.isChecked()) {
                        topicInfo = new PublishTopicInfo(publishImageContent.getText().toString(), "1", groupId, addressText.getText().toString());
                    } else {
                        topicInfo = new PublishTopicInfo(publishImageContent.getText().toString(), "1", groupId, "");
                    }
                    MainPublishImageBean publishBean = new MainPublishImageBean();
                    publishBean.setGsTopicInfo(topicInfo);
                    //发布文字
                    mPresenter.onSetDoPublishList(JSON.toJSONString(publishBean));
                }
            }
        }
    }

    /**
     * 发布图片
     */
    private void publishImages() {

        List<PublishImageFileBean> lists = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            PublishImageFileBean publishImageFileBean = new PublishImageFileBean(String.valueOf(i), imageList.get(i));
            lists.add(publishImageFileBean);
        }
        //是否显示地理位置
        if (publishImageContentCheck.isChecked()) {
            topicInfo = new PublishTopicInfo(publishImageContent.getText().toString(), "1", groupId, "");
        } else {
            topicInfo = new PublishTopicInfo(publishImageContent.getText().toString(), "1", groupId, "");
        }
        MainPublishImageBean publishBean = new MainPublishImageBean();
        publishBean.setGsTopicInfo(topicInfo);
        publishBean.setFileList(lists);
        //发布图文
        mPresenter.onSetDoPublishList(JSON.toJSONString(publishBean));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 102:
                    String CircleName = data.getStringExtra("CircleName");
                    liftText = publishImageContent.getText().toString();
                    if (!TextUtils.isEmpty(data.getStringExtra("CircleName"))) {
                        publishTopic.setText(CircleName);
                    } else {
                        publishTopic.setText("");
                    }
                    TopicOfConversation = "";
                    publishImageContent.setText(data.getStringExtra("CircleName") + liftText);
                    publishImageContent.setSelection(publishImageContent.getText().length());
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    //compressPath 压缩图片地址
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    if (images.size() > 0) {
                        publishImageBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                        publishImageBtn.setTextColor(getResources().getColor(R.color.color_font_black));
                    }
                    parseLocalMedia(images);
                    break;
                default:
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
        }
        List<UploadImageBean> temp = uploadImageListAdapter.getData();
        temp.remove(temp.size() - 1);
        temp.addAll(data);
        temp.add(new UploadImageBean());
        uploadImageListAdapter.setNewData(temp);

        if (uploadImageListAdapter.getData().size() == 10) {
            uploadImageListAdapter.getData().remove(9);
        }
        uploadImageListAdapter.notifyDataSetChanged();
    }


    @Override
    public void onSetDoPublishSuccess(PublishListBean publishListBean) {
        hideLoadingDialog();
        showBottomToast("发布成功");
        new Handler().postDelayed(() -> {
            EventBus.getDefault().post(new PublishResult());
            finish();
        }, 200);
    }

    @Override
    public void onSetDoPublishFailed(String errMsg) {
        hideLoadingDialog();
        showBottomToast(errMsg);
    }

    @OnClick({R.id.publish_image_btn, R.id.pub_voice_tv_user_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.publish_image_btn:
                setContentIsNull();
                break;
            case R.id.pub_voice_tv_user_agreement:
                Intent intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PUBLIC_USER_AGREEMENT);
                startActivity(intent);
                break;
        }
    }
}
